<template>
  <div class="content">
    <div class="breadcrumb">
      <el-breadcrumb>
        <el-breadcrumb-item :to="{ path: '/commodity/list' }">账号列表</el-breadcrumb-item>
        <el-breadcrumb-item>添加账号</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="operation">
      <el-button @click="router.go(-1)">返回</el-button>
    </div>
    <el-form class="form-box" ref="ruleFormRef" :model="formData" :rules="rules" label-width="120px">
      <el-form-item label="标题" prop="title">
        <el-input :disabled="route.query.review" v-model="formData.title" />
      </el-form-item>
      <!-- <el-form-item label="商品id" prop="account_id">
        <el-input :disabled="route.query.review" v-model="formData.account_id" />
      </el-form-item>
      <el-form-item label="商品编号" prop="number">
        <el-input :disabled="route.query.review" v-model="formData.number" />
      </el-form-item> -->
      <el-form-item label="售价" prop="price">
        <el-input :disabled="route.query.review" v-model="formData.price" type="number" />
      </el-form-item>
      <el-form-item label="最低价(元)" prop="min_price">
        <el-input :disabled="route.query.review" v-model="formData.min_price" type="number" />
      </el-form-item>
      <!-- <el-form-item label="粉丝单价" prop="fans_price">
        <el-input :disabled="route.query.review" v-model="formData.fans_price" type="number" />
      </el-form-item> -->
      <el-form-item label="粉丝数量" prop="fans_num">
        <el-input :disabled="route.query.review" v-model="formData.fans_num" type="number" placeholder="万">
          <template #append>万</template>
        </el-input>
      </el-form-item>

      <!-- <el-form-item label="点赞数量" prop="up_num">
        <el-input :disabled="route.query.review" v-model="formData.up_num" type="number" placeholder="万">
          <template #append>万</template>
        </el-input>
      </el-form-item> -->
      <el-form-item label="点赞比" prop="up_num">
        <el-input :disabled="route.query.review" v-model="formData.up_num"></el-input>
      </el-form-item>
      <!-- <el-form-item label="客户手机号(微信)" prop="phone">
        <el-input :disabled="route.query.review" v-model="formData.phone" />
      </el-form-item> -->
      
      <el-form-item label="业务员微信名" prop="wechat">
        <el-input :disabled="route.query.review" v-model="formData.wechat" />
      </el-form-item>

      <el-form-item label="活跃度" prop="activity_level">
        <el-input :disabled="route.query.review" type="number" v-model="formData.activity_level" />
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input :disabled="route.query.review" v-model="formData.remark" type="textarea" :rows="4" placeholder="请输入备注" />
      </el-form-item>

      <el-form-item label="账号类目" prop="category">
        <div class="checkbox-box">
          <template v-for="item in getDictItems(dicts, 'goods:category')">
            <Checkbox @change="checkedChange" v-model:checkedKeys="formData.category" :id="item.dict_item_id" :title="item.dict_item_title"></Checkbox>
          </template>
        </div>
      </el-form-item>
      <el-form-item label="认证状态" prop="auth_status">
        <div class="checkbox-box">
          <template v-for="item in getDictItems(dicts, 'authentication:status')">
            <Checkbox @change="checkedChange" v-model:checkedKeys="formData.auth_status" :id="item.dict_item_id" :title="item.dict_item_title"></Checkbox>
          </template>
        </div>
      </el-form-item>

      <!-- <el-form-item label="价格区间" prop="price">
        <div class="checkbox-box">
          <template v-for="item in getDictItems(dicts, 'price:range')">
            <Checkbox @change="checkedChange" v-model:checkedKeys="formData.price" :id="item.dict_item_id" :title="item.dict_item_title"></Checkbox>
          </template>
        </div>
      </el-form-item> -->
      <el-form-item label="粉丝画像" prop="fans_bias">
        <div class="checkbox-box">
          <template v-for="item in getDictItems(dicts, 'fan:bias')">
            <Checkbox @change="checkedChange" v-model:checkedKeys="formData.fans_bias" :id="item.dict_item_id" :title="item.dict_item_title"></Checkbox>
          </template>
        </div>
      </el-form-item>
      <el-form-item label="粉丝年龄" prop="fans_age">
        <div class="checkbox-box">
          <template v-for="item in getDictItems(dicts, 'fan:age')">
            <Checkbox @change="checkedChange" v-model:checkedKeys="formData.fans_age" :id="item.dict_item_id" :title="item.dict_item_title"></Checkbox>
          </template>
        </div>
      </el-form-item>
      <!-- <el-form-item label="粉丝数量" prop="fans_num">
        <div class="checkbox-box">
          <template v-for="item in getDictItems(dicts, 'fan:num')">
            <Checkbox @change="checkedChange" v-model:checkedKeys="formData.fans_num" :id="item.dict_item_id" :title="item.dict_item_title"></Checkbox>
          </template>
        </div>
      </el-form-item> -->
      <el-form-item :label="formData.commodity_cate_id == 2 ? '小店状态' : '橱窗状态'" prop="shop_status">
        <div class="checkbox-box">
          <template v-for="item in getDictItems(dicts, 'shop:window:status')">
            <Checkbox @change="checkedChange" v-model:checkedKeys="formData.shop_status" :id="item.dict_item_id" :title="item.dict_item_title"></Checkbox>
          </template>
        </div>
      </el-form-item>

      <el-form-item label="信誉分状态" prop="reputation_score" v-if="formData.commodity_cate_id == 7">
        <el-select v-model="formData.reputation_score" placeholder="请选择">
          <el-option v-for="item in reputationScore" :key="item.id" :label="item.title" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="历史违规" prop="has_violation">
        <div class="checkbox-box">
          <template v-for="item in getDictItems(dicts, 'violation')">
            <Checkbox @change="checkedChange" v-model:checkedKeys="formData.has_violation" :id="item.dict_item_id" :title="item.dict_item_title"></Checkbox>
          </template>
        </div>
      </el-form-item>

      <el-form-item v-if="formData.commodity_cate_id == 2" label="快手粉条" prop="fen_strip">
        <!-- <el-radio-group v-model="formData.fen_strip">
          <el-radio :label="1" size="large">加热正常</el-radio>
          <el-radio :label="2" size="large">加热异常</el-radio>
        </el-radio-group> -->
        <div class="checkbox-box">
          <Checkbox @change="checkedChange" v-model:checkedKeys="formData.fen_strip" :id="1" :title="'加热正常'"></Checkbox>
          <Checkbox @change="checkedChange" v-model:checkedKeys="formData.fen_strip" :id="2" :title="'加热异常'"></Checkbox>
        </div>
      </el-form-item>

      <template v-if="formData.commodity_cate_id == 1">
        <el-form-item label="作品dou+" prop="work_dou">
          <el-radio-group v-model="formData.work_dou">
            <el-radio label="1" size="large">DOU+正常</el-radio>
            <el-radio label="0" size="large">DOU+异常</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="直播dou+" prop="live_dou">
          <el-radio-group v-model="formData.live_dou">
            <el-radio label="1" size="large">DOU+正常</el-radio>
            <el-radio label="0" size="large">DOU+异常</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="dou+户头" prop="dou_account">
          <el-radio-group v-model="formData.dou_account">
            <el-radio label="1" size="large">个人</el-radio>
            <el-radio label="2" size="large">企业</el-radio>
          </el-radio-group>
        </el-form-item>
      </template>

      <el-form-item label="是否更换实名" prop="is_change_real">
        <el-radio-group v-model="formData.is_change_real">
          <el-radio label="1" size="large">是</el-radio>
          <el-radio label="0" size="large">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="星图实名" prop="chart_real" v-if="!['2', '7'].includes(formData.commodity_cate_id)">
        <div class="checkbox-box">
          <template v-for="item in getDictItems(dicts, 'starChart:realname')">
            <Checkbox @change="checkedChange" v-model:checkedKeys="formData.chart_real" :id="item.dict_item_id" :title="item.dict_item_title"></Checkbox>
          </template>
        </div>
      </el-form-item>
      <el-form-item :label="formData.commodity_cate_id == 2 ? '磁力金牛' : '星图权限'" prop="chart_auth">
        <div class="checkbox-box">
          <template v-for="item in getDictItems(dicts, 'starChart:auth')">
            <Checkbox @change="checkedChange" v-model:checkedKeys="formData.chart_auth" :id="item.dict_item_id" :title="item.dict_item_title"></Checkbox>
          </template>
        </div>
      </el-form-item>
      <el-form-item label="直播权限" prop="live_auth">
        <div class="checkbox-box">
          <template v-for="item in getDictItems(dicts, 'live:auth')">
            <Checkbox @change="checkedChange" v-model:checkedKeys="formData.live_auth" :id="item.dict_item_id" :title="item.dict_item_title"></Checkbox>
          </template>
        </div>
      </el-form-item>

      <!-- <el-form-item label="是否热门" prop="is_hot">
        <el-radio-group v-model="formData.is_hot">
          <el-radio :label="1" size="large">是</el-radio>
          <el-radio :label="0" size="large">否</el-radio>
        </el-radio-group>
      </el-form-item> -->
      <!-- <el-form-item label="上架状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :label="1" size="large">上架</el-radio>
          <el-radio :label="0" size="large">下架</el-radio>
        </el-radio-group>
      </el-form-item> -->
      <!-- <el-form-item label="账号分类" prop="commodity_cate_id">
        <div class="checkbox-box">
          <template v-for="item in commodityCates">
            <Checkbox @change="checkedChange" v-model:checkedKeys="formData.commodity_cate_id" :id="item.id" :title="item.title"></Checkbox>
          </template>
        </div>
      </el-form-item> -->
      <el-form-item label="抖音全系分类" prop="commodity_cate_id" v-if="formData.commodity_cate_id == 6">
        <div class="checkbox-box">
          <template v-for="item in getDictItems(dicts, 'service:cate')">
            <Checkbox @change="checkedChange" v-model:checkedKeys="formData.service_cate" :id="item.dict_item_id" :title="item.dict_item_title"></Checkbox>
          </template>
        </div>
      </el-form-item>

      <!-- <el-form-item label="出售状态" prop="sale_status">
        <el-radio-group v-model="formData.sale_status">
          <el-radio :label="1" size="large">在售中</el-radio>
          <el-radio :label="2" size="large">交接中</el-radio>
          <el-radio :label="3" size="large">已售出</el-radio>
        </el-radio-group>
      </el-form-item> -->

      <el-form-item required v-if="['1', '2'].includes(String(formData.commodity_cate_id))" label="对接状态" prop="docking_status">
        <el-radio-group v-model="formData.docking_status">
          <el-radio label="1" size="large">账号实名人</el-radio>
          <el-radio label="2" size="large">账号运营人</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="是否有未成年退款" prop="is_minor_refund">
        <el-radio-group v-model="formData.is_minor_refund">
          <el-radio :label="0" size="large">否</el-radio>
          <el-radio :label="1" size="large">是</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="回访时间" prop="visit_time">
        <el-date-picker
          v-model="formData.visit_time"
          type="datetime"
          placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="详情图">
        <el-upload class="upload-demo" v-model:file-list="fileList" :action="uploadUrlApi" :headers="{
          // AccessToken: 'xxx'
        }" :on-preview="handlePreview" list-type="picture" :before-upload="beforeUpload" :on-success="handleSuccess">
          <el-button v-if="!route.query.review" type="primary">上传</el-button>
          <template #tip>
            <div class="el-upload__tip">
              jpg/png files with a size less than 500kb
            </div>
          </template>
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button v-if="!route.query.review" @click="resetForm(ruleFormRef)">重置</el-button>
        <el-button v-if="!route.query.review" type="primary" @click="submitForm(ruleFormRef)">
          提交
        </el-button>

      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, reactive, ref } from 'vue';
import { Checkbox } from '/@/components/Checkbox';
import { FormRules, FormInstance, ElMessage } from 'element-plus';
import config from '/@/config/index';
import type { UploadProps, UploadUserFile, UploadFile, UploadFiles } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { getSession } from '/@/utils';
import dayjs from 'dayjs';

const baseUrl = config.baseUrl;
const ossUrl = config.ossUrl;
const uploadUrlApi = `${baseUrl}/uploadFile`;

const { proxy }: any = getCurrentInstance();
const router = useRouter();
const route = useRoute();
const formData = reactive({
  title: '', // 标题
  account_id: '', // 商品id
  number: 'test', // 编号
  price: '', // 价格
  fans_price: '1', // 粉丝单价
  phone: '', // 用户手机号
  up_num: '', // 点赞数量
  min_price: '', // 最低价
  wechat: '', // 微信号

  category: [], // 账号类目
  auth_status: '', // 认证状态
  fans_bias: '', // 粉丝偏向
  fans_age: [], // 粉丝年龄
  fans_num: '', // 粉丝数量
  shop_status: '', // 橱窗状态
  has_violation: '', // 有无违规
  chart_real: '', // 星图实名
  chart_auth: '', // 星图权限
  live_auth: '', // 直播权限
  // is_hot: 0, // 是否热门
  status: 0, // 上架状态
  commodity_cate_id: route.query.cateId, // 账号分类
  sale_status: 1,
  service_cate: 1, // 所属抖音服务分类

  reputation_score: '', // 信誉分状态
  docking_status: '', // 对接状态
  work_dou: '', // 作品dou+
  live_dou: '', // 直播dou+
  dou_account: '', // dou+户头
  fen_strip: '', // 快手粉条

  activity_level: 0, // 活跃度
  // 是否更换实名
  is_change_real: 0,
  remark: '',
  is_minor_refund: 0, // 是否有未成年退款
  visit_time: '', // 回访时间
});
const rules = reactive<FormRules>({
  title: [
    { required: true, message: '请输入', trigger: 'blur' }
  ],
});
const ruleFormRef = ref<FormInstance>();

const dicts = reactive<any[]>([]); // 字典
const commodityCates = reactive<any[]>([]); // 账号分类

const checkedChange = (rows) => {
  console.log(rows);
};

// NOTE:查询字典
const getDicts = async () => {
  const res = await proxy.$http.getDicts({
    dictMap: [
      'goods:category', // 类目
      'authentication:status', // 认证状态
      'price:range', // 价格区间
      'fan:bias', // 粉丝偏向
      'fan:age', // 粉丝年龄
      'fan:num', // 粉丝数量
      'shop:window:status', // 橱窗状态
      'violation', // 有无违规
      'starChart:realname', // 星图实名
      'starChart:auth', // 星图权限
      'live:auth', // 直播权限
      'service:cate', // 抖音全系分类
    ]
  });
  if (res.code == config.SUCCESS_CODE) {
    dicts.push(...res.data); 
  }
};

// NOTE:查询账号分类
const commodityCateList = async () => {
  const res = await proxy.$http.commodityCateList();
  if (res.code == config.SUCCESS_CODE) {
    commodityCates.push(...res.data);
  }
};

// NOTE:获取字典
const getDictItems = (dicts: any[], name: string): any[] => {
  let i = dicts.length;
  while (i--) {
    if (dicts[i].name == name) {
      return dicts[i].items;
    }
  }
  return [];
};

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      console.log('submit!', fileList, formData);
      const userInfo = getSession('userInfo');
      let res;
      if (!route.query.id) {
        res = await proxy.$http.addCommodity({
          ...formData,
          admin_user_id: userInfo.id,
          fileList: fileList.value,
          account_id: formData.title, // 给账号id默认值
          visit_time: formData.visit_time ? dayjs(formData.visit_time).format('YYYY-MM-DD HH:mm:ss') : ''
        });
      } else {
        res = await proxy.$http.updateCommodity({
          ...formData,
          fileList: fileList.value,
          account_id: formData.title, // 给账号id默认值
          visit_time: formData.visit_time ? dayjs(formData.visit_time).format('YYYY-MM-DD HH:mm:ss') : ''
        });
      }
      
      if (res.code == config.SUCCESS_CODE) {
        ElMessage({
          message: '操作成功！',
          type: 'success',
        });
        // router.push({
        //   path: '/commodity/list'
        // });
        router.go(-1);
      }
    }
  })
};

// 重置
const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
  fileList.value.length = 0;
}

// const fileList = ref<UploadUserFile[]>();
const fileList = ref<any[]>([]);

// const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
//   console.log(uploadFile, uploadFiles)
// };

const handlePreview: UploadProps['onPreview'] = (file) => {
  console.log(file)

  if (file.url) {
    window.open(file.url)
  }
};

// const handleChange: UploadProps['onChange'] = (uploadFile, uploadFiles) => {
//   // fileList.value = fileList.value.slice(-3);
//   console.log('change', uploadFile, uploadFiles)
//   if (uploadFile.status != 'fail') {

//   }
// }

// 上传图片前
const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  const imgReg = /(jpg|jpeg|png|gif|svg)$/ig;
  if (!imgReg.test(rawFile.type)) {
    ElMessage.error('请上传图片文件!');
    return false;
  }
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!');
    return false;
  }
  return true;
}

// NOTE:上传图片成功
const handleSuccess = (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  for (let i = 0; i < uploadFiles.length; i++) {
    if (uploadFiles[i].response) {
      fileList.value.splice(i, 1);
    }
  }
  if (response.code == config.SUCCESS_CODE) {
    fileList.value.push({
      name: uploadFile.name,
      url: ossUrl + response.data.files[0]?.path,
      path: response.data.files[0]?.path,
    });
  } else {
    alert('上传失败:' + response.msg);
    return false;
  }

  console.log(fileList);
};

// 查询账号详情
const findById = async (id) => {
  const res = await proxy.$http.commodityById({
    id: id
  });
  if (res.code == config.SUCCESS_CODE) {
    for (let key in res.data) {
      formData[key] = res.data[key] == null ? '' : res.data[key];
      if (key === 'category') {
        formData[key] = formData[key] != '' ? formData[key]?.split(',') : [];
      }
      if (key === 'fileList') {
        let files = res.data[key];
        fileList.value.length = 0;
        for (let i = 0; i < files.length; i++) {
          fileList.value.push({
            url: `${config.ossUrl}${files[i].url}`,
            name: files[i].file_name,
            path: files[i].url
          });
        }
      }
    }
    // Object.assign(formData, res.data);
    console.log(formData);
  }
};

const reputationScore = ref(Array(100).fill({}));

reputationScore.value = reputationScore.value.map((item, key) => {
  let newRows: any = {};
  newRows.title = key + 1;
  newRows.id = key + 1;
  return newRows;
});

// 初始化
const init = async () => {
  getDicts();
  commodityCateList();

  if (route.query.id) {
    findById(route.query.id);
  }

  // NOTE:抖音和快手才有对接状态
  if (['1', '2'].includes(formData.commodity_cate_id)) {
    rules['docking_status'] = [
      { required: true, message: '请选择', trigger: 'blur' }
    ];
  }
}

init();
</script>

<style lang="scss" scoped>
.content {
  height: 100%;
  width: 100%;
  margin-bottom: 100px;
  .operation {
    margin: 10px 0;
  }
  .form-box {
    margin-top: 10px;
    max-width: 1000px;
  }

  .checkbox-box {
    display: flex;
    flex-wrap: wrap;

    .checkbox {
      margin-right: 10px;
      margin-bottom: 10px;
    }
  }

  .upload-demo {
    width: 100%;
  }
}
</style>